<template>
    <div class="bg">
<!--        <particles></particles>-->
      <div style="background: white;width:30%;margin:0 auto;">
        <div style="width: 400px;margin: 70px auto">
            <div style="color: black;font-size: 30px;text-align: center;padding: 30px 0">欢迎登录</div>

            <el-form ref="form" :model="form" size="normal" :rules="rules">
                <el-form-item prop="username">
                    <el-input   prefix-icon="el-icon-user-solid" v-model="form.username" clearable=""
                              placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input prefix-icon="el-icon-lock" v-model="form.password" show-password=""
                              placeholder="请输入密码"></el-input>

                </el-form-item>
                <el-form-item>
                    <div style="display: flex">
                        <el-input prefix-icon="el-icon-key" v-model="form.validCode" style="width: 50%;"
                                  placeholder="请输入验证码" clearable=""></el-input>
                        <ValidCode @input="createValidCode" style="margin-left:90px "/>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" style="width: 400px;border-radius: 20px" @keyup.enter.native="login"
                               @click="login ">登 录
                    </el-button>
                </el-form-item>
                <div style="display: flex">
                    <el-form-item>
                        <el-button type="primary" style="border-radius: 20px" @click="open">忘记密码</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" style="margin-left: 230px;border-radius: 20px"
                                   @click="$router.push('/register')">注册
                        </el-button>
                    </el-form-item>
                </div>
            </el-form>
        </div>
      <div style="margin: -83px auto;;width: 321px;text-align: center;display: flex;justify-content: space-between;flex-direction: column">
        <el-divider>其他登录方式</el-divider>
      <div  style="display:flex;justify-content: space-evenly;">
        <img @click="qqLogin('qq')" class="other" src="../assets/img/qq.png"/>
        <img class="other" src="../assets/img/weibo.png"/>
        <img class="other" src="../assets/img/wechat.png"/>
        <img class="other" src="../assets/img/dd.png"/>
      </div>
      <br/>
      <br/>
      </div>

      </div>
        <el-dialog
                title="忘记密码"
                :visible.sync="dialogVisible"
                width="30%">
            <el-form label-width="120px" :model="forms" :rules="rules" ref="forms">
                <el-form-item label="用户名" style="font-weight: bold" prop="username">
                    <el-input v-model="forms.username" placeholder="请输入用户名" style="width: 80%"></el-input>
                </el-form-item>

                <el-form-item label="密码" style="font-weight: bold" prop="password">
                    <el-input v-model="forms.password" type="password" placeholder="请输入新密码" show-password=""
                              style="width: 80%"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button  @click="dialogVisible=false">重置</el-button>
    <el-button type="primary" @click="forget">修改密码</el-button>
  </span>
        </el-dialog>

    </div>
</template>

<script>
    import Particles from '@/components/particles/index'
    import ValidCode from "@/components/ValidCode";
    import request from "@/utils/request";
    import {activeRouter} from "@/utils/permission";
    export default {
        components: {Particles, ValidCode},
        name: "Login",
        data() {
            return {
                dialogVisible: false,
                fullscreenLoading: false,
                validCode: '',
                form: {
                    username: '',
                    password: '',
                },
                forms: {},

                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur'}
                    ],
                }


            }
        },
        created() {
            let that = this;
            document.onkeydown = function (e) {
                e = window.event || e;
                if (that.$route.path == '/login' && (e.code == 'Enter' || e.code == 'enter')) {//验证在登录界面和按得键是回车键enter
                    that.login('form');//登录函数
                }
            }
        },
        methods: {

          // 第三方登录
          qqLogin(value) {
            console.log(value)
            if (value == 'qq') {
              var _this = this;
              request.get('/qq/oauth').then(resp => {
                console.log(resp)
                //window.open(resp.data.result, "_blank")
                var width = width || 900;
                var height = height || 540;
                var left = (window.screen.width - width) / 2;
                var top = (window.screen.height - height) / 2;
                var win = window.open(resp.data, "_self",
                    "toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, left=" +
                    left + ", top=" + top + ", width=" + width + ", height=" + height);
                console.log(_this)
                console.log(win)
                //监听登录窗口是否关闭,登录成功后 后端返回关闭窗口的代码
                // var listener = setInterval(function () {
                //   //监听窗口是否关闭
                //   if (win.closed) {
                //     //进入这个if代表后端验证成功!直接跳转路由
                //     clearInterval(listener);//关闭监听
                //     //跳转路由
                //     var path = _this.$route.query.redirect;
                //     console.log("================>",_this.$route)
                //     console.log("========path========>",path)
                //     _this.$router.replace({
                //       path:
                //           path === "/" || path === undefined ? "/admin/dashboard" : path
                //     });
                //     _this.$router.go(0) //刷新
                //   }
                // }, 500)
              }).catch(fail => {
                console.error(fail)
              })
            }
          },

            // 接收验证码组件提交的 4位验证码
            createValidCode(data) {
                this.validCode = data
            },

            open() {
                this.dialogVisible = true
            },

            //重置密码
            reset(){
                request.put("sys/reset",this.forms).then(res=>{
                    console.log(res)
                    if (res.data.code === '0') {
                        this.$message({
                            message:'密码重置成功，默认密码为:123456',
                            type:'success'
                        })
                        this.dialogVisible=false
                    }else{
                        this.$message({
                            message:res.data.msg,
                            type:'warning'
                        })
                    }

                })

            },

            //忘记密码
            forget() {
                this.$refs['forms'].validate((valid) => {
                    if (valid) {
                        request.put("/sys/forget", this.forms).then(res => {
                            console.log(res)
                            if (res.data.code === '0') {
                                this.$message({
                                    message: '密码修改成功',
                                    type: 'success'
                                })
                                this.forms = {}
                                this.dialogVisible = false
                            } else {
                                this.$message({
                                    type: "'warning",
                                    message: res.data.msg,

                                })
                                this.dialogVisible = false
                                this.forms = {}
                            }
                        })
                    }
                })
            },
            //登录
            login() {

                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        if (!this.form.validCode) {
                            this.$message.warning("请填写验证码")
                            return
                        }
                        if (this.form.validCode.toLowerCase() !== this.validCode.toLowerCase()) {
                            this.$message.warning("验证码错误")
                            return
                        }
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });
                        setTimeout(() => {
                            loading.close();

                            request.post("/sys/login", this.form).then(res => {

                                if (res.code === '0') {
                                    this.$message({
                                        type: "success",
                                        message: "登录成功"
                                    })

                                    sessionStorage.setItem("user", JSON.stringify(res.data))  // 缓存用户信息
                                    const permissions=res.data.permissions;
                                    activeRouter(permissions)


                                    this.$router.push("/")  //登录成功之后进行页面的跳转，跳转到主页
                                } else {
                                    this.$message({
                                        type: "error",
                                        message: res.msg
                                    })
                                }
                            })
                        }, 1000);
                    }
                })

            }
        }
    }
</script>

<style>
    .bg {
        background-image: url("../assets/register.jpg");
        width: 100%;
        height: 100vh;
        overflow: hidden;
        background-repeat: no-repeat;
        background-size: 100%;
    }
    .other {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      border: 1px solid rgba(0, 0, 0, .1);
      text-align: center;
    }
    .el-input {

        border-radius: 10px;
    }
</style>


